package library.utils;

import android.os.Handler;
import android.os.Looper;
import android.os.Message;

import java.lang.ref.WeakReference;

/**
 * Created by Mr.Fan on 2016/10/31.
 */

public abstract class InnerHandler<Object> extends Handler {
    private WeakReference<Object> reference;

    private InnerHandler() {
    }

    private InnerHandler(Callback callback) {
        super(callback);
    }

    private InnerHandler(Looper looper) {
        super(looper);
    }

    private InnerHandler(Looper looper, Callback callback) {
        super(looper, callback);
    }

    public InnerHandler(Object object) {
        this.reference = new WeakReference<>(object);
    }

    public InnerHandler(Object object, Looper looper) {
        super(looper);
        this.reference = new WeakReference<>(object);
    }

    public InnerHandler(Object object, Callback callback) {
        super(callback);
        this.reference = new WeakReference<>(object);
    }

    public InnerHandler(Object object, Looper looper, Callback callback) {
        super(looper, callback);
        this.reference = new WeakReference<>(object);
    }

    protected Object getObject() {
        return reference != null ? reference.get() : null;
    }

    @Override
    public void handleMessage(Message msg) {
        Object object = getObject();
        if (object != null)
            handleMessage(msg, object);
    }

    protected abstract void handleMessage(Message msg, Object object);
}
